package pref.junx.flybird.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import pref.junx.flybird.app.AppContext;
import pref.junx.flybird.cookie.PersistentCookieStore;

/**
 * Created by JunX on 17/5/12.
 */

public class OkHttpUtils {

    // 连接超时时间
    private static final int CONNECT_TIMEOUT = 10;
    // 写入超时时间
    private static final int WRITE_TIMEOUT = 10;
    // 读取超时时间
    private static final int READ_TIMEOUT = 10;

    // OkHttpClient实例
    private static OkHttpClient okHttpClient;

    // 设置缓存目录
    private static File cacheDirectory = new File(Environment.getExternalStorageDirectory() + "/FlyBird/cache/", "cache");
    private static Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024);

    /**
     * 获取OkHttpClient
     * @return
     */
    public static OkHttpClient getOkHttpClient() {

        if (null == okHttpClient) {
            okHttpClient = new OkHttpClient.Builder()
                    .cookieJar(new CookiesManager())
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                    // 添加拦截器
                    .addInterceptor(new BaseInterceptor())
                    .addNetworkInterceptor(new MInterceptor())
                    // 设置请求读写的超时时间
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    .cache(cache)
                    .build();
        }
        return okHttpClient;
    }

    private static class BaseInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            if (!checkNet(AppContext.getInstance().getApplicationContext())) {
                request = request
                        .newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            return chain.proceed(request);
        }
    }

    private static class MInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!checkNet(AppContext.getInstance().getApplicationContext())) {
                request = request
                        .newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            Response originalResponse = chain.proceed(request);
            return originalResponse
                    .newBuilder()
                    // 在这里生成新的响应并修改它的响应头
                    .header("Cache-Control", "public, max-age=0")
                    .removeHeader("Pragma").build();
        }
    }



    /***
     * 检查网络
     *
     * @param context
     * @return
     */
    public static boolean checkNet(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对像
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info == null || !info.isAvailable()) {
                    return false;
                } else {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * Cookies管理器
     */
    private static class CookiesManager implements CookieJar {

        private final PersistentCookieStore cookieStore = new PersistentCookieStore(AppContext.getInstance().getApplicationContext());

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            if (cookies != null && cookies.size() > 0) {
                for (Cookie item : cookies) {
                    cookieStore.add(url, item);
                }
            }
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            List<Cookie> cookies = cookieStore.get(url);
            return cookies;
        }
    }

}
